import { CookieManager, CookieData } from './CookieManager';

export interface InterceptorConfig {
  enabled: boolean;
  autoInject: boolean;
  autoExtract: boolean;
  platformPatterns: Record<string, string[]>;
}

export class CookieInterceptor {
  private cookieManager: CookieManager;
  private config: InterceptorConfig;
  private isIntercepting: boolean = false;

  constructor(tabId: string, config?: Partial<InterceptorConfig>) {
    this.cookieManager = new CookieManager(tabId);
    this.config = {
      enabled: true,
      autoInject: true,
      autoExtract: true,
      platformPatterns: {
        '抖音': ['douyin.com', 'iesdouyin.com'],
        '快手': ['kuaishou.com', 'gifshow.com'],
        '小红书': ['xiaohongshu.com'],
        '微博': ['weibo.com'],
        'B站': ['bilibili.com']
      },
      ...config
    };
  }

  // 启动拦截器
  start(): void {
    if (this.isIntercepting) return;
    
    this.isIntercepting = true;
    this.interceptFetchRequests();
    this.interceptXmlHttpRequests();
    
    console.log(`Cookie拦截器已启动 - Tab ID: ${this.cookieManager['tabId']}`);
  }

  // 停止拦截器
  stop(): void {
    this.isIntercepting = false;
    console.log(`Cookie拦截器已停止 - Tab ID: ${this.cookieManager['tabId']}`);
  }

  // 拦截Fetch请求
  private interceptFetchRequests(): void {
    const originalFetch = window.fetch;
    
    window.fetch = async (input, init) => {
      if (!this.config.enabled || !this.isIntercepting) {
        return originalFetch(input, init);
      }

      const url = typeof input === 'string' ? input : input.url;
      const request = new Request(input, init);
      
      // 检查是否是支持的平台
      if (!this.isSupportedPlatform(url)) {
        return originalFetch(input, init);
      }

      // 自动注入Cookie
      if (this.config.autoInject) {
        const cookieHeader = this.cookieManager.generateCookieHeader(url);
        if (cookieHeader) {
          request.headers.set('Cookie', cookieHeader);
        }
      }

      try {
        const response = await originalFetch(request);
        
        // 自动提取Cookie
        if (this.config.autoExtract) {
          this.extractCookiesFromResponse(response, url);
        }
        
        return response;
      } catch (error) {
        console.error('Fetch请求拦截失败:', error);
        throw error;
      }
    };
  }

  // 拦截XMLHttpRequest
  private interceptXmlHttpRequests(): void {
    const originalOpen = XMLHttpRequest.prototype.open;
    const originalSend = XMLHttpRequest.prototype.send;

    XMLHttpRequest.prototype.open = function(method: string, url: string, ...args: any[]) {
      this._url = url;
      return originalOpen.apply(this, [method, url, ...args]);
    };

    XMLHttpRequest.prototype.send = function(data?: any) {
      if (!this.config?.enabled || !this.isIntercepting) {
        return originalSend.call(this, data);
      }

      const url = this._url;
      
      // 检查是否是支持的平台
      if (!this.isSupportedPlatform(url)) {
        return originalSend.call(this, data);
      }

      // 自动注入Cookie
      if (this.config.autoInject) {
        const cookieHeader = this.cookieManager.generateCookieHeader(url);
        if (cookieHeader) {
          this.setRequestHeader('Cookie', cookieHeader);
        }
      }

      // 监听响应
      this.addEventListener('readystatechange', () => {
        if (this.readyState === 4 && this.config?.autoExtract) {
          this.extractCookiesFromXHR(this, url);
        }
      });

      return originalSend.call(this, data);
    };
  }

  // 从Fetch响应中提取Cookie
  private extractCookiesFromResponse(response: Response, url: string): void {
    const setCookieHeader = response.headers.get('Set-Cookie');
    if (setCookieHeader) {
      this.cookieManager.parseSetCookieHeader(setCookieHeader, url);
    }
  }

  // 从XHR响应中提取Cookie
  private extractCookiesFromXHR(xhr: XMLHttpRequest, url: string): void {
    const setCookieHeader = xhr.getResponseHeader('Set-Cookie');
    if (setCookieHeader) {
      this.cookieManager.parseSetCookieHeader(setCookieHeader, url);
    }
  }

  // 检查URL是否属于支持的平台
  private isSupportedPlatform(url: string): boolean {
    try {
      const urlObj = new URL(url);
      const hostname = urlObj.hostname;
      
      // 检查所有平台模式
      for (const patterns of Object.values(this.config.platformPatterns)) {
        for (const pattern of patterns) {
          if (hostname.includes(pattern) || hostname.endsWith(pattern)) {
            return true;
          }
        }
      }
      
      return false;
    } catch {
      return false;
    }
  }

  // 手动设置Cookie
  setCookie(cookie: CookieData): void {
    this.cookieManager.setCookie(cookie);
  }

  // 手动获取Cookie
  getCookie(name: string): CookieData | undefined {
    return this.cookieManager.getCookie(name);
  }

  // 获取所有Cookie
  getAllCookies(): CookieData[] {
    return this.cookieManager.getAllCookies();
  }

  // 批量导入Cookie
  importCookies(cookies: CookieData[]): void {
    cookies.forEach(cookie => this.cookieManager.setCookie(cookie));
  }

  // 导出所有Cookie
  exportCookies(): string {
    return this.cookieManager.exportCookies();
  }

  // 更新配置
  updateConfig(newConfig: Partial<InterceptorConfig>): void {
    this.config = { ...this.config, ...newConfig };
    
    if (this.config.enabled && !this.isIntercepting) {
      this.start();
    } else if (!this.config.enabled && this.isIntercepting) {
      this.stop();
    }
  }

  // 获取当前状态
  getStatus(): { isIntercepting: boolean; cookieCount: number } {
    return {
      isIntercepting: this.isIntercepting,
      cookieCount: this.getAllCookies().length
    };
  }

  // 清理所有Cookie
  clearCookies(): void {
    this.cookieManager.clearAll();
  }
}

// 全局拦截器管理器
export class GlobalCookieInterceptor {
  private static instance: GlobalCookieInterceptor;
  private interceptors: Map<string, CookieInterceptor> = new Map();

  private constructor() {}

  static getInstance(): GlobalCookieInterceptor {
    if (!GlobalCookieInterceptor.instance) {
      GlobalCookieInterceptor.instance = new GlobalCookieInterceptor();
    }
    return GlobalCookieInterceptor.instance;
  }

  // 为特定标签页创建拦截器
  createInterceptor(tabId: string, config?: Partial<InterceptorConfig>): CookieInterceptor {
    const interceptor = new CookieInterceptor(tabId, config);
    this.interceptors.set(tabId, interceptor);
    return interceptor;
  }

  // 获取特定标签页的拦截器
  getInterceptor(tabId: string): CookieInterceptor | undefined {
    return this.interceptors.get(tabId);
  }

  // 移除特定标签页的拦截器
  removeInterceptor(tabId: string): boolean {
    const interceptor = this.interceptors.get(tabId);
    if (interceptor) {
      interceptor.stop();
      return this.interceptors.delete(tabId);
    }
    return false;
  }

  // 启动所有拦截器
  startAll(): void {
    this.interceptors.forEach(interceptor => interceptor.start());
  }

  // 停止所有拦截器
  stopAll(): void {
    this.interceptors.forEach(interceptor => interceptor.stop());
  }

  // 获取所有拦截器状态
  getAllStatus(): Record<string, { isIntercepting: boolean; cookieCount: number }> {
    const status: Record<string, { isIntercepting: boolean; cookieCount: number }> = {};
    this.interceptors.forEach((interceptor, tabId) => {
      status[tabId] = interceptor.getStatus();
    });
    return status;
  }
}